package com.bstek.rest;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 接口返回值包装类
 * 
 * @author hans
 * @date 2022年9月17日
 * @company www.bstek.com
 * @param <T>
 */
public class Result<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	private int code;

	private String msg;

	private String time;

	private T data;

	private Result() {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
		this.time = sdf.format(new Date());
	}

	private Result(IResultCode resultCode) {
		this(resultCode, null, resultCode.getMsg());
	}

	private Result(IResultCode resultCode, String msg) {
		this(resultCode, null, msg);
	}

	private Result(IResultCode resultCode, T data) {
		this(resultCode, data, resultCode.getMsg());
	}

	private Result(IResultCode resultCode, T data, String msg) {
		this(resultCode.getCode(), data, msg);
	}
	/**
	 * 返回状态码
	 *
	 * @param resultCode 状态码
	 * @param <T>        泛型标识
	 * @return ApiResult
	 */
	public static <T> Result<T> result(IResultCode resultCode) {
		return new Result<>(resultCode);
	}


	public static <T> Result<T> result(IResultCode resultCode, String msg) {
		return new Result<>(resultCode, msg);
	}

	public static <T> Result<T> data(T data) {
		return data(data, "处理成功");
	}

	public static <T> Result<T> data(T data, String msg) {
		return data(ResultCode.SUCCESS.code, data, msg);
	}

	public static <T> Result<T> data(int code, T data, String msg) {
		return new Result<>(code, data, data == null ? "承载数据为空" : msg);
	}

	public static <T> Result<T> success(String msg) {
		return new Result<>(ResultCode.SUCCESS, msg);
	}
	public static <T> Result<T> fail() {
		return new Result<>(ResultCode.FAILURE, ResultCode.FAILURE.getMsg());
	}

	public static <T> Result<T> fail(String msg) {
		return new Result<>(ResultCode.FAILURE, msg);
	}
	public static <T> Result<T> condition(boolean flag) {
		return flag ? success("处理成功") : fail("处理失败");
	}
	
	private Result(int code, T data, String msg) {
		this.code = code;
		this.data = data;
		this.msg = msg;
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
		this.time = sdf.format(new Date());
	}


	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getTime() {
		return time;
	}

	public void setTime(String time) {
		this.time = time;
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}

}
